<template>
  <el-card v-loading="loading" shadow="hover" style="height: 100%; position: relative">
    <div slot="header" style="text-align: center; font-size: 20px;font-weight: bolder;color: #666; padding: 10px">
      <span>导入抽检得分完成情况报表</span>
    </div>
    <el-form ref="importForm" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="检查项版本" prop="versionCode">
        <el-select v-model="form.versionCode" style="width: 100%" filterable clearable placeholder="请选择检查项版本">
          <el-option v-for="(item, index) in list" :key="index" :label="item.versionName" :value="item.versionCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="检查项编码" prop="checkCode">
        <el-input v-model.trim="form.checkCode" placeholder="请输入检查项编码" :maxlength="255" />
      </el-form-item>
      <el-form-item label="Excel工作表名" prop="sheetName">
        <el-input v-model.trim="form.sheetName" placeholder="请输入文件名称" :maxlength="255" />
      </el-form-item>
    </el-form>
    <div style="display:flex;justify-content: center; margin-top: 50px;">
      <div>
        <input type="file" accept=".xls,.xlsx" ref="uploadCheckRef" @click="addFileClick" @change="getUploadFile($event, exportError)" style="display: none;">
        <el-button size="small" type="primary" @click="execlTemplateUpload('uploadCheckRef')">校验模板</el-button>
      </div>
      <div style="margin-left: 30px;">
        <input type="file" accept=".xls,.xlsx" ref="uploadImportRef" @click="addFileClick" @change="getUploadFile($event,importRdcData)" style="display: none;">
        <el-button size="small" type="primary" @click="execlTemplateUpload('uploadImportRef')">导入</el-button>
      </div>
      <!--<el-upload
        ref="uploadCheckRef"
        :headers="headers"
        :action="CHECK_FILE_UPLOAD_URL"
        with-credentials
        :data="form"
        :show-file-list="false"
        name="file"
        accept=".xls,.xlsx"
        :before-upload="beforeUpload"
        :on-error="onUploadError"
        :on-success="onUploadSuccess"
      >
        <el-button slot="default" size="small" type="primary">校验模板</el-button>
      </el-upload>-->
      <!--<el-upload
        ref="uploadImportRef"
        :action=" IMPORT_FILE_UPLOAD_URL"
        :headers="headers"
        with-credentials
        :data="form"
        :show-file-list="false"
        name="file"
        accept=".xls,.xlsx"
        :before-upload="beforeUpload"
        :on-error="onUploadError"
        :on-success="onUploadSuccess"
      >
        <el-button slot="default" size="small" style="margin-left: 30px;" type="primary">导入</el-button>
      </el-upload>-->
    </div>
  </el-card>
</template>

<script>
import { getToken } from '@/utils/auth'
import { IMPORT_FILE_UPLOAD_URL, CHECK_FILE_UPLOAD_URL, exportError, importRdcData } from '@/api/statement/exportFile'
import { listVersion } from '@/api/checkScore/cqEval'
export default {
  name: 'ImportRdcData',
  components: {
  },
  props: {
    projects: { type: Array, default: () => [] }
  },
  data() {
    return {
      IMPORT_FILE_UPLOAD_URL,
      CHECK_FILE_UPLOAD_URL,
      exportError,
      importRdcData,
      form: {
        versionCode: '',
        checkCode: '',
        sheetName: ''
      },
      headers: {
        Authorization: ''
      },
      rules: {
        versionCode: [
          { required: true, message: '请选择版本', trigger: 'blur' }
        ],
        sheetName: [
          { required: true, message: '请输入Excel工作表名称', trigger: 'blur' }
        ]
      },
      total: 0,
      list: [],
      queryParams: {
        pageNum: 1,
        pageSize: 1000
      },
      loading: false
    }
  },
  computed: {
  },
  created() {
    if (getToken()) {
      this.headers.Authorization = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    this.getList()
  },
  methods: {
    async getList() {
      this.loading = true
      const res = await listVersion(this.queryParams).catch(() => false)
      this.loading = false
      if (res === false) return

      const data = res.data || []
      data.map(i => {
        i.isEnableLoading = false
        i.removeLoading = false
      })
      this.list = data
      this.total = res.total || 0
    },
    execlTemplateUpload(strRef) {
      this.$refs.importForm.validate((valid) => {
        if (valid) {
          this.$refs[strRef].click()
        }
      })
    },
    addFileClick(event) {
      console.log(11)
      event.target.value = null
    },
    getUploadFile(event, func) {
      this.loading = true
      const file = event.target.files[0]
      const formData = new FormData()
      formData.append('file', file)
      for (const key in this.form) {
        formData.append(key, this.form[key])
      }
      func(formData).then(data => {
        let msg = ''
        const fileName = sessionStorage.getItem('cqFileName') || file.name
        if (data instanceof Blob && data.size > 10) {
          var elink = document.createElement('a')
          var blob = new Blob([data])
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          elink.click()
          msg = `报表模板校验完成,校验结果请查看文件：${fileName}`
          if (func === this.importRdcData) {
            msg = `报表上传出错,错误结果请查看文件：${fileName}`
          }
        } else {
          msg = '报表模板校验成功'
          if (func === this.importRdcData) {
            msg = '报表数据导入成功'
          }
        }
        this.$message({message: msg, type: 'success', duaring: 5000})
      }).finally(() => {
        setTimeout(() => {
          this.loading = false
        }, 1500)
      })
    },
    beforeUpload(file) {
      console.log(file)
      // this.form.sheetName = file.name
      // const isAccept = acceptTypeList.includes(file.type)
      // const isLt10M = file.size / 1024 / 1024 < 10
      // if (!isAccept) this.msgError('上传图片只能是 JPG/PNG 格式!')
      // if (!isLt10M) this.msgError('上传文件大小不能超过 100MB!')

      // const isOk = isAccept && isLt10M
      // if (!this.uploading) this.uploading = isOk
      // return isOk
    },
    onUploadError(err, file, fileList) {
      this.msgError(`上传失败 ${err?.msg || ''}`)
    },
    async onUploadSuccess(res, file, fileList) {
      console.log(res, file, fileList)
      if (res.code !== 200) {
        this.msgError(`解析失败: ${res.msg || ''}`)
      } else {
        this.msgSuccess('上传成功')
      }
    }
  }
}
</script>

<style scoped>

</style>
